/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2011
 */

package com.tech15.core.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javacommon.base.BaseManager;
import javacommon.base.EntityDao;
import javacommon.util.DateTools;
import javacommon.util.PropertiesUtil;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.org.rapid_framework.page.Page;

import com.tech15.core.dao.AttachDao;
import com.tech15.core.model.Attach;
import com.tech15.core.vo.query.AttachQuery;

/**
 * @author 胡作正 email:zuozhenghu@sina.com
 * @version 1.0
 * @since 1.0
 */

@Service
@Transactional
public class AttachManager extends BaseManager<Attach,java.lang.String>{

	private AttachDao attachDao;
	public void setAttachDao(AttachDao dao) {
		this.attachDao = dao;
	}
	public EntityDao getEntityDao() {
		return this.attachDao;
	}
	
	@Transactional(readOnly=true)
	public Page findPage(AttachQuery query) {
		return attachDao.findPage(query);
	}
	
	public void delete(String sql){
		attachDao.delete(sql);
	}
	
	public void delete(String tablename,String tableid){
		//attachDao.delete("delete attach t where  t.tablename='"+tablename+"' and t.tableid='"+tableid+"'");
		List<Attach> list = attachDao.findByTableNameAndTableId(tablename, tableid);
		String uploadPath = PropertiesUtil.getResourceBundle().getString("uploadPath");
		for(Attach attach : list){
			File file = new File(uploadPath+"/"+attach.getPath());
			file.delete();
		}
		attachDao.deleteAll(list);
	}
	
	/**
	 * 批量上传附件
	 * @param realpath					路径名
	 * @param username					上传者
	 * @param tablename					表名
	 * @param tableid					表id
	 * @param attachFiles				附件列表
	 * @param attachFilesFileName		附件名称
	 * @param attachFilesContentType	附件类型
	 * @return
	 */
	public boolean saveAttachs(String realpath,Long userid,String tablename,String tableid,List<File> attachFiles,List<String> attachFilesFileName,List<String> attachFilesContentType){
		String allowUploadPath = PropertiesUtil.getResourceBundle().getString("allowUploadPath");
		if(allowUploadPath.equals("true")){
			String uploadPath = PropertiesUtil.getResourceBundle().getString("uploadPath");
			realpath = uploadPath;
		}
		if(attachFiles != null && attachFiles.size() > 0){
			String dyPath = java.text.MessageFormat.format("{0,date,yyyyMM}", new Object[]{new java.util.Date()});
        	File savedir = new File(realpath+"\\"+dyPath);
            if(!savedir.exists()){   
                  savedir.mkdirs();
            }
            for (int i=0; i < attachFiles.size(); i++){
            	/*根据时间生成新的文件名*/
            	String newName = java.text.MessageFormat.format("{0,date,yyyyMMddhhmmssS}", new Object[]{new java.util.Date()})+i;
            	String fileName = attachFilesFileName.get(i);
            	//System.out.println(fileName);
            	/*获取文件后缀*/
				String postfix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
				/*文件路径*/
				String newFilepath = newName+postfix;
                File savefile = new File(savedir,newFilepath);
                try {
                	/*上传文件*/
					FileUtils.copyFile(attachFiles.get(i), savefile);
					/*构造附件信息*/
					Attach attach = new Attach();
					attach.setName(attachFilesFileName.get(i));
					attach.setPath(dyPath+"/"+newFilepath);
					attach.setAttachSize(attachFiles.get(i).length());
					attach.setContType(attachFilesContentType.get(i));
					attach.setPostfix(postfix);
					attach.setUserid(userid);
					attach.setUpTime(DateTools.getCurrentTime());
					attach.setTablename(tablename);
					attach.setTableid(tableid);
					/*保存附件信息*/
					attachDao.save(attach);
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}  
            }
            return true;
        }else{
        	return false;
        }
	}
	/**
	 * 上传附件
	 * @param realpath					路径名
	 * @param userid					上传者
	 * @param tablename					表名
	 * @param tableid					表id
	 * @param attachFile				附件
	 * @param attachFileFileName		附件名称
	 * @param attachFileContentType		附件类型
	 * @return
	 */
	public boolean saveAttach(String realpath,Long userid,String tablename,String tableid,File attachFile,String attachFileFileName,String attachFileContentType){
		String allowUploadPath = PropertiesUtil.getResourceBundle().getString("allowUploadPath");
		if(allowUploadPath.equals("true")){
			String uploadPath = PropertiesUtil.getResourceBundle().getString("uploadPath");
			realpath = uploadPath;
		}
		if(attachFile != null){
			String dyPath = java.text.MessageFormat.format("{0,date,yyyyMM}", new Object[]{new java.util.Date()});
			File savedir = new File(realpath+"\\"+dyPath);
            if(!savedir.exists()){   
                  savedir.mkdirs();
            }
            /*根据时间生成新的文件名*/
        	String newName = java.text.MessageFormat.format("{0,date,yyyyMMddhhmmssS}", new Object[]{new java.util.Date()});
        	String fileName = attachFileFileName;
        	//System.out.println(fileName+"\t"+attachFile.getName());
        	/*获取文件后缀*/
			String postfix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			/*文件路径*/
			String newFilepath = newName+postfix;
            File savefile = new File(savedir,newFilepath);
            try {
            	/*上传文件*/
				FileUtils.copyFile(attachFile, savefile);
				/*构造附件信息*/
				Attach attach = new Attach();
				attach.setUserid(userid);
				attach.setName(attachFileFileName);
				attach.setPath(dyPath+"/"+newFilepath);
				attach.setAttachSize(attachFile.length());
				attach.setContType(attachFileContentType);
				attach.setPostfix(postfix);
				attach.setUpTime(DateTools.getCurrentTime());
				attach.setTablename(tablename);
				attach.setTableid(tableid);
				/*保存附件信息*/
				attachDao.save(attach);
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
            return true;
        }else{
        	return false;
        }
	}
	
	public String saveImage(String realpath,File attachFile,String attachFileFileName,String attachFileContentType){
		File savedir = new File(realpath);
        if(!savedir.exists()){   
              savedir.mkdirs();
        }
        /*根据时间生成新的文件名*/
    	String newName = java.text.MessageFormat.format("{0,date,yyyyMMddhhmmssS}", new Object[]{new java.util.Date()});
    	if(attachFile != null && attachFileFileName != null){
    		String fileName = attachFileFileName;
    		/*获取文件后缀*/
    		String postfixIndex = fileName.substring(fileName.lastIndexOf("."), fileName.length());
    		/*文件路径*/
    		String newIndexFilepath = newName+postfixIndex;
    		File saveIndexfile = new File(savedir,newIndexFilepath);
    		/*上传文件*/
    		try {
    			FileUtils.copyFile(attachFile, saveIndexfile);
    			return "images/"+newIndexFilepath;
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	return null;
	}
	
	public List<Attach> findByTableNameAndId(String tablename,String id){
		return attachDao.findByTableNameAndId(tablename,id);
	}
	
	/**更新文件内容*/
	public boolean updateAttach(Attach attach,String realpath,File attachFile){
		if(attachFile != null){
			String allowUploadPath = PropertiesUtil.getResourceBundle().getString("allowUploadPath");
			if(allowUploadPath.equals("true")){
				String uploadPath = PropertiesUtil.getResourceBundle().getString("uploadPath");
				realpath = uploadPath;
			}
			String path = realpath + attach.getPath();
			//System.out.println(path+"====");
			File savefile = new File(path);
			try {
				FileUtils.copyFile(attachFile, savefile);
			}catch (IOException e){
				e.printStackTrace();
			}
            return true;
        }else{
        	return false;
        }
	}
}
